<template>
  <div class="add-notice">
    <div class="schedule-name ismemory">
      <el-form label-position="top" :model="noticeObj" class="demo-form-stacked" ref="noticeObj" :rules="rules">
        <div class="pb10 notice-title">
          <el-form-item prop="title" :label="$t('configLazyLoad.noticeConfig.noticeName')">
            <el-input v-model="noticeObj.title" :placeholder="$t('configLazyLoad.noticeConfig.inputName')" style="width: 100%"></el-input>
          </el-form-item>
        </div>
        <div class="pb10 notice-content">
          <el-form-item prop="content" :label="$t('configLazyLoad.noticeConfig.noticeContent')">
            <el-input type="textarea" :rows="4" v-model="noticeObj.content" :placeholder="$t('configLazyLoad.noticeConfig.inputContent')" style="width: 100%"></el-input>
          </el-form-item>
        </div>
        <div class="pb10">
          <el-form-item :label="$t('configLazyLoad.noticeConfig.noticeTime')">
            <el-radio-group v-model="publicDate">
              <el-radio label="1">{{$t('configLazyLoad.noticeConfig.oneDay')}}</el-radio>
              <el-radio label="3">{{$t('configLazyLoad.noticeConfig.threeDays')}}</el-radio>
              <el-radio label="7">{{$t('configLazyLoad.noticeConfig.oneWeek')}}</el-radio>
              <el-radio label="14">{{$t('configLazyLoad.noticeConfig.twoWeeks')}}</el-radio>
              <el-radio label="manual">{{$t('webchat.customTime')}}</el-radio>
              </el-radio-group>
            <el-input v-model="customDays" style="width: 100px;padding: 0px 5px" :disabled="disFlag"><template slot="append">{{$t('public.day2')}}</template></el-input>
          </el-form-item>
        </div>
        <div class="pb10" style="clear: both">
          <el-form-item :label="$t('configLazyLoad.noticeConfig.noticeLevel2')">
            <el-radio-group v-model="noticeObj.level">
              <el-radio label="common">{{$t('channelsettings.serviceNumber6')}}</el-radio>
              <el-radio label="important">{{$t('configLazyLoad.noticeConfig.important')}}</el-radio>
              </el-radio-group>
          </el-form-item>
        </div>
        <div>
          <el-form-item :label="$t('public.attach')">
            <div>
              <el-button :class="'iconfont icon-fujian'" :id="btnId" :disabled="disabled" :type="btnStyle.type" :size="btnStyle.size">{{btnStyle.text}}</el-button>
              <span style="font-size:12px;margin-left:20px;">{{$t('business.fileMoreThanTenMb')}}</span>
              <div class="process-ui" v-if="progressUi.show">
                <span>{{progressUi.fileName}}</span>
                <el-progress :text-inside="true" :stroke-width="18" :percentage="progressUi.percent" :status="progressUi.type"></el-progress>
              </div>
            </div>
            <div v-for="(file, index) in noticeObj.attachs" v-if="noticeObj.attachs.length" class="fujian-div">
              <a :href="common.getUrl(file,{useAttname: true})" download target="_blank" class="text-color">{{file.name}}</a>
              <span class="delete" @click="deleteFile(file.id, index)" style="cursor: pointer">
                  <i class="el-icon-close"></i>
                </span>
              <!--<globalPopup :url="qiniu7moorDomain+file.id+'?attname='+file.name"-->
                           <!--:key="qiniu7moorDomain+file.id"-->
                           <!--@showBigImage="showBigImage"-->
                           <!--@deleteFile="deleteFile"-->
                           <!--:name="file.name"-->
                           <!--:currObj="{url: qiniu7moorDomain+file.id, id: file.id, index: index, disabled: disabled, showDelBtn: true}"-->
                           <!--:srcUrl="qiniu7moorDomain+file.id" :imgObj="[]"></globalPopup>-->
            </div>
            <input type="hidden" v-model.trim="noticeObj.attachs"/>
          </el-form-item>
        </div>
        <div class="pb10">
          <el-form-item :label="$t('configLazyLoad.noticeConfig.noticeScope')">
          <!-- <owner-tree-select ref="ownerTree"
                             businessType="notice"
                             :isNotice="true"
                             :_scopeArray="treeArray"
                             @owner-change="handleOwnerChange"
                             v-show="false"
                             @owner-reset="handleOwnerReset"
                             @tree-data="treedata">
          </owner-tree-select> -->
          <owner-tree style="padding-top:10px" ref="treeTransfer" :_scopeArray="treeArray"></owner-tree>
          <!-- <el-button @click="test">测试</el-button> -->
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div style="clear: both">
      <el-button @click="submit('save')" class='primary_btn'>{{$t('configLazyLoad.noticeConfig.save1')}}</el-button>
      <el-button type="primary" @click="submit('publish')" class='primary_btn'>{{$t('configLazyLoad.noticeConfig.save2')}}</el-button>
    </div>
  </div>
</template>
<script>
  import {deepClone, getCurrentDate} from '@/utils/m7Utils'
  import * as uuid from 'uuid'
  import { common } from '@/utils/cosUrl'
  import globalPopup from '@/components/ui-modules/affix/globalPopup.vue'
  import {uploadTo7moorDomain, qiniu7moorDomain} from '@/utils/qiniuUtils'
  import AgentAssign from '@/components/public-modules/agent-assign/AgentAssign.vue'
  import OwnerTreeSelect from '@/components/public-modules/agent-tree/OwnerTreeSelect.vue'
  import OwnerTree from '@/components/public-modules/agent-tree/OwnerTree.vue'
  import treeTransfer from '@/components/ui-modules/treeTransfer/treeTransfer.vue'
  export default {
    name: 'addOrEditNotice',
    data () {
      return {
        btnStyle: {
          text: this.$t('customer.attach'),
          type: 'text',
          size: '',
          icon: true
        },
        btnId: 'btn' + uuid.v1(),
        uploader: '',
        disFlag: true,
        publicDate: '1',
        customDays: '',
        rules: {
          title: [
            {required: true, message: this.$t('validate.required'), trigger: 'blur'}
          ],
          content: [
            {required: true, message: this.$t('validate.required'), trigger: 'blur'}
          ]
        },
        noticeObj: {
          attachs: [],
          title: '',
          content: '',
          level: 'common',
          showScope: {
            ownercom: '',
            ownerdep: '',
            user: ''
          }
        },
        domain: qiniu7moorDomain,
        disabled: false,
        progressUi: {
          show: false,
          percent: 0,
          type: 'success',
          fileName: '',
          disabled: false
        },
        treeArray: [],
        common
      }
    },
    props: {
      isEdit: Boolean,
      noticeInfo: {
        type: Object,
        default: function () {
          return {
            attachs: [],
            title: '',
            content: '',
            level: 'common',
            showScope: {
              ownercom: '',
              ownerdep: '',
              user: ''
            }
          }
        }
      }
    },
    computed: {
      attachmentMaxSize () {
        return this.$store.state.attachmentMaxSize
      }
    },
    methods: {
      deleteFile (id, index) {
        let _Arr = []
        if (this.noticeObj.attachs.length !== 0) {
          _Arr = deepClone(this.noticeObj.attachs)
          _Arr.splice(index, 1)
        }
        let data = {
          _id: this.noticeInfo._id,
          delId: id,
          attachs: _Arr
        }
        this.$store.dispatch('deleteNoticeAttach', data).then((res) => {
          if (res.success) {
            this.noticeObj.attachs.splice(index, 1)
          }
        })
      },
      initUploadNoticeFile (ev) {
        let account = this.$store.state.session.user.account
        let that = this
        let filters = {}
        let fileAdded = function (up, files) {
          console.log('fileAdd')
        }
        let beforeUpload = function (up, file) {
          that.progressUi.show = true
          that.progressUi.percent = 0
          that.progressUi.fileName = file.name
          console.log('beforeUpload')
        }
        let uploadProgress = function (up, file) {
          that.progressUi.percent = file.percent
          console.log('uploadProgress')
        }
        let uploadComplete = function () {
          that.progressUi.show = false
          console.log('uploadComplete')
        }
        let fileUploaded = function (up, file, info) {
          let res = JSON.parse(info || '{}')
          const id = that.$store.state.isUseQiniu ? res.key : (that.$store.state.fileDomain.cos7moorTestDomain + file.fileKey)
          let obj = {
            name: file.name,
            type: file.type,
            id,
          }
          that.noticeObj.attachs.push(obj)
          if (that.require === 'required') {
            that.$refs.form.validate((valid) => {
            })
          }
        }
        let error = function (up, err, errTip) {
          if (err.code === -600) {
            that.$message.error(that.$t('business.attachmentMaxDescription20'))
          }
          that.progressUi.show = false
          console.log('uploadError ' + errTip)
        }
        let key = function (up, file) {
          let date = getCurrentDate()
          let today = new Date()
          let time = today.getTime()
          let fileName = file.name
          // let fileSuffix = ''
          // if (fileName) {
          //   fileSuffix = fileName.substring(fileName.lastIndexOf('.'), fileName.length)
          // }
          const isQiniu = that.$store.state.isUseQiniu
          const cmpKey = isQiniu ? 'km' : 'm7-common'
          let key = account + `/${cmpKey}/` + date + '/' + time + '/' + uuid.v1() + '/' + fileName
          return key
        }
        this.uploader = uploadTo7moorDomain(this.$store.state.fileDomain.cos7moorTestDomain, this.$store.state.session.user._id, this.btnId, filters, fileAdded, beforeUpload, uploadProgress, uploadComplete, fileUploaded, error, key, this.attachmentMaxSize, true)
      },
      handleOwnerChange (obj) {
        let emitData = { selectName: obj.type, selectValue: `${obj._id}__${obj.displayName || obj.label}`, name: obj.name }
        console.log(emitData)
      },
      handleOwnerReset (name) {
        let emitData = { selectName: 'ownercom', selectValue: '' }
        if (name) {
          emitData.name = name
        }
        console.log(emitData)
      },
      treedata(data,todata){
          this.$refs.treeTransfer.setdata(data,todata)
      },
      handleData () {
        if (this.isEdit) {
          let _noticeData = deepClone(this.noticeInfo)
          this.noticeObj.attachs = _noticeData.attachs || []
          this.noticeObj.title = _noticeData.title
          this.noticeObj.content = _noticeData.content
          this.noticeObj.level = _noticeData.level
          this.noticeObj._id = _noticeData._id
          this.noticeObj.showScope = {
            user: '',
            ownercom: '',
            ownerdep: ''
          }
          if (_noticeData.showDays.type === 'quick') {
            this.publicDate = _noticeData.showDays.value + ''
            this.customDays = ''
          } else {
            this.publicDate = 'manual'
            this.customDays = _noticeData.showDays.value
          }
          let _scopeArray = []
          if (_noticeData.showScope.ownercom) {
            _scopeArray.push(_noticeData.showScope.ownercom)
          }
          if (_noticeData.showScope.ownerdep) {
            let _data = _noticeData.showScope.ownerdep.split(',')
            _scopeArray = _scopeArray.concat(_data)
          }
          if (_noticeData.showScope.user) {
            let _data = _noticeData.showScope.user.split(',')
            _scopeArray = _scopeArray.concat(_data)
          }
          this.treeArray = _scopeArray
        } else {
          this.publicDate = '1'
          this.customDays = ''
          this.treeArray = []
          this.noticeObj = {
            attachs: [],
            title: '',
            content: '',
            level: 'common',
            showScope: {
              ownercom: '',
              ownerdep: '',
              user: ''
            }
          }
        }
      },
      getOwnerTreeValue(now_data){
        // let now_data = this.$refs.treeTransfer.$refs.treeTransfer.self_to_data
        let arr = []
        let unfold = function(data){
          for (let i = 0; i < data.length; i++) {
            const element = data[i]
            if(element.children){
              unfold(element.children)
            }else{
              arr.push(element)
            }
          }
        }
        unfold(now_data)
        return (arr)
      },
      submit (saveType) {
        console.log(this.noticeObj)
        this.$refs.noticeObj.validate((valid) => {
          if (valid) {
            let scopeFlag = false
            // let _nodes = this.$refs.ownerTree.getCheckedNodes()
            let _nodes = this.getOwnerTreeValue(this.$refs.treeTransfer.$refs.treeTransfer.self_to_data)
            let _owercom = []
            let _user = []
            let _ownerdep = []
            _nodes.forEach(item => {
              if (item._id === 'all') {
                _owercom.push(item._id)
              }
              if (item.type === 'owner') {
                _user.push(item._id)
              }
              if (item.type === 'ownerdep') {
                _ownerdep.push(item._id)
              }
            })
            if (_user.length !== 0) {
              this.noticeObj.showScope.user = _user.join(',')
            }
            if (_owercom.length !== 0) {
              this.noticeObj.showScope.ownercom = _owercom.join(',')
            }
            if (_ownerdep.length !== 0) {
              this.noticeObj.showScope.ownerdep = _ownerdep.join(',')
            }
            if ((this.noticeObj.showScope.user === '') && (this.noticeObj.showScope.ownercom === '') && (this.noticeObj.showScope.ownerdep === '')) {
              scopeFlag = true
            }
            if (scopeFlag) {
              this.$message.error(this.$t('configLazyLoad.noticeConfig.chooseScope'))
              return
            }
            let _data = {
              attachs: this.noticeObj.attachs || [],
              title: this.noticeObj.title,
              content: this.noticeObj.content,
              showScope: this.noticeObj.showScope,
              level: this.noticeObj.level
            }
            if (this.publicDate === 'manual') {
              let reg = new RegExp('^[0-9]*$')
              if (this.customDays === '') {
                this.$message.error(this.$t('configLazyLoad.noticeConfig.errorTip3'))
                return
              } else if (!reg.test(this.customDays)) {
                this.$message.error(this.$t('configLazyLoad.noticeConfig.errorTip4'))
                return
              }
              _data.showDays = {
                type: 'custom',
                value: parseInt(this.customDays)
              }
            } else {
              _data.showDays = {
                type: 'quick',
                value: parseInt(this.publicDate)
              }
            }
            _data.status = saveType
            if (this.isEdit) {
              _data._id = this.noticeObj._id
              this.$store.dispatch('updateNotice', _data).then(res => {
                if (res && res.success) {
                  this.$emit('refresh')
                  this.$message.success(this.$t('channelsettings.schedule26'))
                } else {
                  this.$message.error(this.$t('channelsettings.schedule27'))
                }
              })
            } else {
              console.log('11111')
              this.$store.dispatch('createNotice', _data).then(res => {
                if (res && res.success) {
                  this.$message.success(this.$t('channelsettings.Voicelibrary5'))
                  this.$emit('refresh')
                } else {
                  this.$message.error(this.$t('channelsettings.Voicelibrary6'))
                }
              })
            }
//            this.serviceObj.Order = parseInt(this.serviceObj.Order)
//            console.log(this.serviceObj)
          }
        })
      }
    },
    watch: {
      publicDate () {
        if (this.publicDate === 'manual') {
          this.disFlag = false
        } else {
          this.disFlag = true
        }
      },
      isEdit () {
        this.$nextTick(() => {
          this.$refs['noticeObj'].clearValidate()
          this.handleData()
        })
      },
      noticeInfo () {
        this.$nextTick(() => {
          this.handleData()
          this.$refs['noticeObj'].clearValidate()
        })
      }
    },
    components: {
      globalPopup,
      AgentAssign,
      OwnerTreeSelect,
      treeTransfer,
      OwnerTree
    },
    beforeDestroy () {
      this.uploader && this.uploader.destroy && this.uploader.destroy()
      this.uploader = null
    },
    mounted () {
      if (!this.disabled) {
        this.initUploadNoticeFile()
      }
    },
    beforeMount () {
      this.handleData()
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .add-notice
    padding 20px
    .notice-title
      .el-input
        width 300px
    .ismemory
      clear both
    .pb10
      padding-bottom 10px
    .icon-zuixiaohua
      font-size: 12px;
      color: #737373;
      padding: 0px 10px;
    .tishi
      color $c-prompt
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 16px
      border-radius 50%
      margin-left 2px
      .iconfont
        font-size 10px
        color $c-main
  .fujian-div
    display: inline-block;
    background-color: #d1f6f8;
    line-height: normal;
    padding: 5px;
    margin-right: 10px;
    height: 20px;
    font-size: 14px;
    vertical-align: top;
    .text-color
      color: #000;
      vertical-align: middle;
    .delete
      color: $c-main;
      padding-left: 10px;
      vertical-align: middle;
</style>
